# -*- coding: utf-8 -*-

from django.shortcuts import RequestContext, render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import Permission
from django.contrib.auth.models import Group
from django.contrib.auth import login, authenticate
from django.utils.translation import ugettext_lazy as _

from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib import messages


from models import Estado, Fornecedor
from forms import FornecedorPasso2, FornecedorPasso3, FornecedorPasso4, FornecedorHomologar

@login_required
@user_passes_test(lambda u: u.has_perm('fornecedor.can_view_list'))
def lista(request):
    f = Fornecedor.objects.order_by('estado__descricao').select_related()
    # messages.success(request, 'Fornecedor a salvo com sucesso!')
    # messages.error(request, 'Fornecedor a salvo com sucesso!')
    # messages.warning(request, 'Fornecedor a salvo com sucesso!')
    return render_to_response(
            'lista.html',
            {'fornecedores': f,
             'LIS': 1,
             },
            RequestContext(request),
            )

@login_required
@user_passes_test(lambda u: u.has_perm('fornecedor.can_view'))
def view(request):

    if request.user.has_perm('fornecedor.is_fornecedor') and request.user.is_staff == False:
        if hasattr(request.user, 'fornecedor'):
            f = request.user.fornecedor
        else:
            messages.error(request, 'Você deve completar o segundo passo do seu cadastro.')
            return HttpResponseRedirect(reverse('cadastro_2'))

    else:
        f = request.GET.get('f', False)
        if f:
            try:
                f = Fornecedor.objects.get(id=f)
            except Fornecedor.DoesNotExist:
                messages.error(request, u'Fornecedor %s não encontrado.' % f)
                return HttpResponseRedirect(reverse('lista_fornecedor'))
        else:
            return HttpResponseRedirect(reverse('lista_fornecedor'))

    return render_to_response(
            'view_fornecedor.html',
            {'VIE': 1,
             'fornecedor': f},
            RequestContext(request),
            )

@login_required
@user_passes_test(lambda u: u.has_perm('fornecedor.can_homolog'))
def alterar_indice(request, id):
    form = None
    f = get_object_or_404(Fornecedor, id=id)
    if request.method == 'POST':
        form = FornecedorHomologar(request.POST, instance=f)
        if form.is_valid():
            form.save()
            messages.success(request, u'Indice alterado com sucesso.')
            return HttpResponse('<html><body onload="window.parent.$.fancybox.close()"></body></html>')

    c = {'form': form or FornecedorHomologar(instance=f),
         'f': f}
    return render_to_response(
        'alterar_indice.html',
        c,
        RequestContext(request))

@login_required
@user_passes_test(lambda u: u.has_perm('fornecedor.can_homolog'))
def homologar(request, id):
    f = get_object_or_404(Fornecedor, id=id)
    if f.can_homologar():
        if request.method == 'POST':
            form = FornecedorHomologar(request.POST, instance=f)
            if form.is_valid():
                if f.homologar(form.instance.indice):
                    messages.success(request, u'Fornecedor %s homologado com sucesso.' % f)
                    return HttpResponse('<html><body onload="window.parent.$.fancybox.close()"></body></html>')
        else:
            form = FornecedorHomologar(instance=f)
        return render_to_response('homologar.html', {'form': form, 'f': f}, RequestContext(request))
    else:
        messages.success(request, u'Fornecedor %s não pode ser homologado.' % f)
    return HttpResponseRedirect(reverse('lista_fornecedor'))

@login_required
@user_passes_test(lambda u: u.has_perm('fornecedor.can_homolog'))
def cancelar(request, id):
    f = get_object_or_404(Fornecedor, id=id)
    f.cancelar()
    messages.success(request, 'Cadastro do fornecedor %s cancelado.' % f)
    return HttpResponseRedirect(reverse('lista_fornecedor'))

def cadastro(request):

    if request.user.is_authenticated():
        try:
            id = Fornecedor.objects.filter(usuario = request.user).values('id')[0]['id']
            return HttpResponseRedirect(reverse('cadastro_2') + '?f=%s' % id)
        except IndexError:
            messages.warning(request, 'Não é possivel cadastrar fornecedores estando logado.')
            return HttpResponseRedirect(reverse('lista_fornecedor'))

    if request.method == 'POST':
        # Formulario de criação de novo usuario
        form = UserCreationForm(request.POST)
        if form.is_valid():
            # Salva o usuario criado
            user = form.save()
            user.groups.add(Group.objects.get(name="Fornecedor"))
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            if username and password:
                # Faz login com o novo usuario
                user = authenticate(username=username, password=password)
                if user is not None:
                    login(request, user)
                    return HttpResponseRedirect(reverse('cadastro_2'))
    else:
        form = UserCreationForm()

    return render_to_response(
            'cadastro.html',
            {'form': form,
             'passo': 1,
             'CAD': 1,
             },
            RequestContext(request),
            )

@user_passes_test(lambda u: u.has_perm('fornecedor.is_fornecedor'))
def cadastro_2(request):

    try:
        fornecedor = Fornecedor.objects.get(usuario=request.user)
    except Fornecedor.DoesNotExist:
        fornecedor = Fornecedor(usuario=request.user)

    if request.method == 'POST':
        form = FornecedorPasso2(request.POST, instance=fornecedor)
        if form.is_valid():
            form.instance.estado = Estado.objects.get(id=1)
            fornecedor = form.save()
            return HttpResponseRedirect(reverse('cadastro_3'))
    else:
        form = FornecedorPasso2(instance=fornecedor)

    return render_to_response(
            'cadastro.html',
            {'form': form,
             'passo' : 2,
             'EDI': 1,
             },
            RequestContext(request),
            )

@user_passes_test(lambda u: u.has_perm('fornecedor.is_fornecedor'))
def cadastro_3(request):

    fornecedor = get_object_or_404(Fornecedor, usuario=request.user)

    if request.method == 'POST':
        form = FornecedorPasso3(request.POST, request.FILES, instance=fornecedor)
        if form.is_valid():
            fornecedor = form.save(commit=False)
            fornecedor.set_doc_empresa_entregue()
            return HttpResponseRedirect(reverse('cadastro_4'))
    else:
        form = FornecedorPasso3()

    return render_to_response(
            'cadastro.html',
            {'form': form,
             'fornecedor': fornecedor,
             'passo': 3,
             'EDI': 1,
             },
            RequestContext(request),
            )

@user_passes_test(lambda u: u.has_perm('fornecedor.is_fornecedor'))
def cadastro_4(request):

    fornecedor = get_object_or_404(Fornecedor, usuario=request.user)

    if request.method == 'POST':
        form = FornecedorPasso4(request.POST, request.FILES, instance=fornecedor)
        if form.is_valid():
            fornecedor = form.save(commit=False)
            fornecedor.set_doc_produtos_entregue()
            messages.success(request, 'Fornecedor %s salvo com sucesso!' % unicode(fornecedor))
            return HttpResponseRedirect(reverse('index'))
    else:
        form = FornecedorPasso4()

    return render_to_response(
            'cadastro.html',
            {'form': form,
             'fornecedor': fornecedor,
             'passo': 4,
             'EDI': 1},
            RequestContext(request),
            )
